<!--
 * @Author: saltman
 * @Date: 2024-12-11 15:26:13
 * @LastEditTime: 2025-05-01 15:38:59
 * @LastEditors: saltman
 * @Description: 
 * @FilePath: \open_-innovation_-platform_-front\src\components\PublishJob.vue
 * coding sheep......
-->
<template>
  <div class="flex-col page">
    <div class="content-container">
      <div class="form-card">
        <!-- 标题区域 -->
        <div class="section-header">
          <div class="section-title">
            <div class="title-bar"></div>
            <h2>发布任务</h2>
          </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
          <!-- 基本信息部分 -->
          <div class="form-section">
            <div class="form-group">
              <label class="form-label">标题<span class="required">*</span></label>
              <el-input
                  v-model="form.title"
                  placeholder="请输入标题"
                  class="custom-input"
              />
            </div>

            <div class="form-group">
              <label class="form-label">标签<span class="required">*</span></label>
              <el-select
                  v-model="form.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请输入标签，按回车确认"
                  class="custom-select"
              >
                <el-option
                    v-for="item in existingTags"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </div>

            <!-- 任务设置部分 -->
            <div class="form-group settings-group">
              <label class="form-label">任务设置<span class="required">*</span></label>
              <div class="settings-container">
                <div class="setting-item">
                  <span class="setting-label">奖励：</span>
                  <el-input
                      v-model="form.money"
                      type="number"
                      placeholder="0"
                      class="setting-input"
                  >
                    <template #suffix>r/题</template>
                  </el-input>
                </div>

                <div class="setting-item">
                  <span class="setting-label">组数：</span>
                  <el-input
                      v-model="form.groupCount"
                      type="number"
                      placeholder="0"
                      class="setting-input"
                      @change="handleGroupCountChange"
                  >
                    <template #suffix>组</template>
                  </el-input>
                </div>

                <div class="setting-item">
                  <span class="setting-label">每组人数：</span>
                  <el-input
                      v-model="form.groupSize"
                      type="number"
                      placeholder="0"
                      class="setting-input"
                      @change="updateTotalParticipants"
                  >
                    <template #suffix>人</template>
                  </el-input>
                </div>

                <div class="setting-item">
                  <span class="setting-label">总人数：</span>
                  <el-input
                      v-model="form.totalParticipants"
                      type="number"
                      disabled
                      class="setting-input"
                  >
                    <template #suffix>人</template>
                  </el-input>
                </div>

                <div class="setting-item">
                  <span class="setting-label">开始：</span>
                  <el-date-picker
                      v-model="form.startTime"
                      type="date"
                      placeholder="选择日期"
                      class="setting-input"
                  />
                </div>

                <div class="setting-item">
                  <span class="setting-label">结束：</span>
                  <el-date-picker
                      v-model="form.endTime"
                      type="date"
                      placeholder="选择日期"
                      class="setting-input"
                  />
                </div>
              </div>
            </div>

            <!-- 文件上传部分 -->
            <div class="form-group">
              <label class="form-label">任务文件</label>
              <el-upload
                  class="custom-upload"
                  list-type="text"
                  :auto-upload="false"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleFileRemove"
                  :on-change="handleFileChange"
                  :limit="1"
              >
                <el-button type="primary">
                  <i class="el-icon-upload"></i>
                  <span>点击上传</span>
                </el-button>
                <template #tip>
                  <div class="upload-tip">支持任意格式文件，单个文件不超过10MB</div>
                </template>
              </el-upload>
            </div>

            <!-- 封面上传部分 -->
            <div class="form-group">
              <label class="form-label">封面图片<span class="required">*</span></label>
              <el-upload
                  class="custom-upload"
                  :auto-upload="false"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleImageRemove"
                  :on-change="handleImageChange"
                  :limit="1"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>

            <!-- 编辑器部分 -->
            <div class="form-group">
              <label class="form-label">任务描述<span class="required">*</span></label>
              <div class="editor-container">
                <div ref="quillEditor" class="quill-editor"></div>
              </div>
            </div>

            <!-- 添加大模型设置部分 -->
            <div class="form-group">
              <label class="form-label">大模型设置</label>
              <div class="ai-settings-container">
                <el-switch
                    v-model="form.enableAI"
                    active-text="启用大模型"
                    inactive-text="不启用"
                    @change="handleAIEnableChange"
                />

                <div class="ai-options" v-if="form.enableAI">
                  <el-select
                      v-model="form.aiMode"
                      placeholder="选择大模型模式"
                      class="custom-select"
                  >
                    <el-option label="内置大模型" value="internal"/>
                    <el-option label="外置大模型" value="external"/>
                  </el-select>

                  <el-switch
                      v-model="form.useMirror"
                      active-text="使用镜像发布"
                      inactive-text="不使用镜像"
                      :disabled="!form.enableAI"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button @click="resetForm" class="reset-btn">重置</el-button>
            <el-button @click="submitForm" type="primary" class="submit-btn">发布</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Quill from "quill";
import "quill/dist/quill.snow.css";
import {postFormDataRequest} from "@/api/api";

export default {
  components: {},
  props: {},
  data() {
    return {
      isSubmitting: false,
      wordCount: 0,
      maxWordCount: 2000,
      form: {
        title: "",
        description: "",
        tags: [],
        imageSrc: "",
        groupCount: 1,
        groupSize: 1,
        totalParticipants: 1,
        money: 0,
        file: "",
        startTime: "",
        endTime: "",
        image: "",
        enableAI: false,
        aiMode: 'internal',
        useMirror: false,
      },
      dialogImageUrl: "",
      dialogVisible: false,
      existingTags: ["活动", "讲座", "比赛", "志愿者"],
    };
  },

  methods: {
    //上传失败
    uploadFileError(err, file, fileList) {
      this.$message.error("上传失败！");
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 保存表单数据到localStorage
    saveFormToLocalStorage() {
      try {
        // 创建表单数据的副本，排除文件对象（不能被序列化）
        const formDataCopy = {...this.form};
        delete formDataCopy.file;
        delete formDataCopy.image;

        // 保存编辑器内容
        if (this.quill) {
          formDataCopy.description = this.quill.root.innerHTML;
        }

        localStorage.setItem('publishJob_formData', JSON.stringify(formDataCopy));
        console.log('表单数据已保存到localStorage');
      } catch (error) {
        console.error('保存表单数据失败:', error);
      }
    },
    // 从localStorage恢复表单数据
    restoreFormFromLocalStorage() {
      try {
        const savedData = localStorage.getItem('publishJob_formData');
        if (savedData) {
          const parsedData = JSON.parse(savedData);

          // 恢复基本表单字段
          Object.keys(parsedData).forEach(key => {
            if (key !== 'file' && key !== 'image') {
              this.form[key] = parsedData[key];
            }
          });

          // 恢复编辑器内容
          if (parsedData.description && this.quill) {
            this.quill.root.innerHTML = parsedData.description;
            this.updateWordCount();
          }

          console.log('表单数据已从localStorage恢复');
        }
      } catch (error) {
        console.error('恢复表单数据失败:', error);
      }
    },
    async submitForm() {
      // 防止重复提交
      if (this.isSubmitting) {
        return;
      }

      // 表单验证
      if (!this.form.title.trim()) {
        this.$message.error("请输入任务标题");
        return;
      }
      if (this.form.tags.length === 0) {
        this.$message.error("请至少选择一个标签");
        return;
      }
      if (!this.form.imageSrc) {
        this.$message.error("请上传一张封面图片");
        return;
      }
      if (!this.form.groupSize || this.form.groupSize <= 0) {
        this.$message.error("每组人数必须为正数");
        return;
      }
      if (!this.form.groupCount || this.form.groupCount <= 0) {
        this.$message.error("组数必须为正数");
        return;
      }
      if (!this.form.startTime) {
        this.$message.error("请选择开始时间");
        return;
      }
      if (!this.form.endTime) {
        this.$message.error("请选择结束时间");
        return;
      }
      if (!this.quill.root.innerHTML.trim()) {
        this.$message.error("请输入任务描述");
        return;
      }

      this.form.description = this.quill.root.innerHTML;
      this.isSubmitting = true;

      // 创建加载对话框
      const loading = this.$loading({
        lock: true,
        text: '正在上传任务信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 设置超时提示
      const timeoutId = setTimeout(() => {
        loading.text = '上传时间较长，请耐心等待...';
      }, 5000);

      try {
        const formData = new FormData();

        // 添加基础数据
        const jobData = {
          title: this.form.title,
          description: this.form.description,
          tags: this.form.tags,
          groupCount: this.form.groupCount,
          groupSize: this.form.groupSize,
          totalParticipants: this.form.totalParticipants,
          money: this.form.money,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
          enableAI: this.form.enableAI ? 1 : 0,
          aiMode: this.form.enableAI ? this.form.aiMode : null,
          useMirror: this.form.enableAI ? (this.form.useMirror ? 1 : 0) : 0,
        };
        formData.append("job", JSON.stringify(jobData));

        // 添加文件列表
        if (this.form.file) {
          formData.append("file", this.form.file);
          loading.text = '正在上传任务文件...';
        }

        // 添加封面图片
        if (this.form.image) {
          formData.append("image", this.form.image);
          loading.text = '正在上传封面图片...';
        }

        const response = await postFormDataRequest("/jobs", formData);

        // 清除超时提示
        clearTimeout(timeoutId);
        loading.close();

        // 等待一小段时间确保后端处理完成
        await new Promise(resolve => setTimeout(resolve, 1000));

        this.$message({
          message: "发布成功",
          type: "success",
        });

        // 提交成功后重置表单并清除localStorage中的数据
        this.resetForm();
        localStorage.removeItem('publishJob_formData');
      } catch (error) {
        clearTimeout(timeoutId);
        loading.close();

        console.error("表单提交错误:", error);
        this.$message({
          message: "发布失败，请稍后重试",
          type: "error",
          duration: 3000
        });
      } finally {
        this.isSubmitting = false;
      }
    },
    resetForm() {
      this.form.title = "";
      this.form.description = "";
      this.form.tags = [];
      this.form.imageSrc = "";
      this.form.groupCount = 1;
      this.form.groupSize = 1;
      this.form.totalParticipants = 1;
      this.form.money = 0;
      this.form.file = "";
      this.form.startTime = "";
      this.form.endTime = "";
      this.form.image = "";
      this.form.enableAI = false;
      this.form.aiMode = 'internal';
      this.form.useMirror = false;
      this.quill.root.innerHTML = "";
      this.clearEditor();

      // 重置表单后清除localStorage中的数据
      localStorage.removeItem('publishJob_formData');
    },
    initializeQuill() {
      const initialHeight = 200; // 初始高度
      this.$refs.quillEditor.style.height = `${initialHeight}px`; // 设置初始高度

      const editor = this.$refs.quillEditor;
      // 初始化 Quill 编辑器
      this.quill = new Quill(editor, {
        theme: "snow", // 使用 snow 主题
        placeholder: "   请输入描述...", // 默认显示的提示文字
        modules: {
          toolbar: [
            [{header: "1"}, {header: "2"}, {font: []}],
            [{list: "ordered"}, {list: "bullet"}],
            ["bold", "italic", "underline"],
            [{align: []}],
            ["link"],
            ["image"],
          ],
        },
      });

      this.quill.on("text-change", () => {
        this.updateWordCount();
        this.adjustHeight(initialHeight);
        // 编辑器内容变化时保存表单数据
        this.saveFormToLocalStorage();
      });

      // 初始化后尝试恢复数据
      this.restoreFormFromLocalStorage();
    },
    adjustHeight(initialHeight) {
      // 获取编辑器的内容容器
      const editorContent = this.$refs.quillEditor.querySelector(".ql-editor");
      if (editorContent) {
        // 使用 Quill 的 getContents 方法获取 Delta 格式的内容
        const delta = this.quill.getContents();

        // 初始化内容高度，基于初始高度
        let contentHeight = initialHeight;

        // 遍历 Delta 内容
        delta.ops.forEach((op) => {
          if (typeof op.insert === "string") {
            // 按每行的高度累计（假设每行约 20px 高度）
            const lines = op.insert.split("\n").length - 1;
            contentHeight += lines * 20; // 可根据实际行高调整
          } else if (op.insert.image) {
            // 为每张图片追加固定高度（假设图片占 150px 高度）
            contentHeight += 350; // 可根据实际图片大小调整
          }
        });

        // 如果计算的内容高度大于初始高度，则调整编辑器高度
        if (contentHeight > initialHeight) {
          this.$refs.quillEditor.style.height = `${contentHeight}px`;
        }
      }
    },
    updateWordCount() {
      const text = this.quill.getText().trim(); // 获取 Quill 编辑器内容
      console.log("Text:", text);
      this.wordCount =
          text.length > this.maxWordCount ? this.maxWordCount : text.length; // 限制最大字数
    },
    clearEditor() {
      this.quill.setText(""); // 清空编辑器内容
      this.updateWordCount(); // 更新字数统计
    },
    handlePictureCardPreview(file) {
      console.log("url是", file.url);
      this.dialogimageSrc = file.url;
      this.dialogVisible = true;
    },
    handleFileUploadSuccess(response, file, fileList) {
      // console.log('response',response);
      const fullFilePath = `http://localhost:8081${response}`;
      console.log("完整的文件路径:", fullFilePath);

      // 将新文件路径添加到 fileList 数组
      this.form.fileList.push(fullFilePath);
      console.log(this.form.fileList);
    },
    handleImageUploadSuccess(response, file, fileList) {
      // console.log('response',response);

      const fullImageSrc = `http://localhost:8081${response}`;
      console.log("完整的图片URL:", fullImageSrc);

      // 保存封面图片路径
      this.form.imageSrc = fullImageSrc;
    },
    handleFileRemove(file, fileList) {
      const removedFilePath = `http://localhost:8081${file.response}`;
      // 从 fileList 中移除被删除的文件路径
      const index = this.form.fileList.indexOf(removedFilePath);
      if (index > -1) {
        this.form.fileList.splice(index, 1);
      }

      // 文件移除时更新localStorage
      this.form.file = null;
      this.saveFormToLocalStorage();
    },
    handleImageRemove(file, fileList) {
      // 清空封面图片路径
      this.form.imageSrc = "";
      this.form.image = null;

      // 图片移除时更新localStorage
      this.saveFormToLocalStorage();
    },
    handleFileChange(file, fileList) {
      this.form.file = file.raw;
      // 文件变化时保存表单数据（不包括文件对象）
      this.saveFormToLocalStorage();
    },
    handleImageChange(file, fileList) {
      this.form.image = file.raw;
      this.form.imageSrc = file.url;
      // 图片变化时保存表单数据（不包括图片对象）
      this.saveFormToLocalStorage();
    },
    handleAIEnableChange(value) {
      if (!value) {
        // 如果禁用大模型，重置相关选项
        this.form.aiMode = 'internal';
        this.form.useMirror = false;
      }
      // AI设置变化时保存表单数据
      this.saveFormToLocalStorage();
    },
    // 处理组数变化
    handleGroupCountChange(value) {
      this.form.groupCount = Math.max(1, parseInt(value) || 1);
      this.updateTotalParticipants();
      // 组数变化时保存表单数据
      this.saveFormToLocalStorage();
    },
    // 更新总人数
    updateTotalParticipants() {
      const groupCount = Math.max(1, parseInt(this.form.groupCount) || 1);
      const groupSize = Math.max(1, parseInt(this.form.groupSize) || 1);
      this.form.totalParticipants = groupCount * groupSize;
      // 总人数更新时保存表单数据
      this.saveFormToLocalStorage();
    },
  },
  mounted() {
    // 在 mounted 生命周期钩子中初始化 Quill 编辑器
    this.initializeQuill();

    // 添加表单字段变化的监听
    this.$watch('form.title', () => this.saveFormToLocalStorage());
    this.$watch('form.tags', () => this.saveFormToLocalStorage());
    this.$watch('form.money', () => this.saveFormToLocalStorage());
    this.$watch('form.groupSize', () => this.saveFormToLocalStorage());
    this.$watch('form.startTime', () => this.saveFormToLocalStorage());
    this.$watch('form.endTime', () => this.saveFormToLocalStorage());
  },
  // 添加beforeDestroy钩子，确保在组件销毁前保存数据
  beforeDestroy() {
    this.saveFormToLocalStorage();
  },
};
</script>

<style scoped>
.page {
  background-color: #f2f4f7;
  min-height: 100vh;
  padding: 20px 0;
  font-family: "Cera-Bold", sans-serif;
}

.content-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 40px;
}

.form-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
}

.section-header {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-bar {
  width: 4px;
  height: 20px;
  background-color: #e66721;
  border-radius: 2px;
}

.section-title h2 {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.form-content {
  padding: 24px 0;
  max-width: 1200px;
  margin: 0 auto;
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.settings-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  background: #f5f7fa;
  padding: 24px;
  border-radius: 8px;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.setting-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  min-width: 60px;
  line-height: 32px;
}

.setting-input {
  flex: 1;
}

.custom-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  padding: 32px;
  text-align: center;
  background: #fafafa;
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
}

.quill-editor {
  min-height: 400px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.reset-btn {
  background: #1f2d3d;
  color: white;
}

.submit-btn {
  background: #e66721;
  border-color: #e66721;
}

.submit-btn:hover {
  background: #d45e1e;
  border-color: #d45e1e;
}

/* 自定义Element UI组件样式 */
:deep(.el-input__inner) {
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
}

:deep(.el-input__suffix) {
  line-height: 32px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-upload--picture-card) {
  border-radius: 8px;
  width: 148px;
  height: 148px;
  line-height: 148px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  border-radius: 8px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .content-container {
    padding: 0 32px;
  }
}

@media (max-width: 992px) {
  .content-container {
    padding: 0 24px;
  }

  .form-card {
    padding: 24px;
  }

  .settings-container {
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .content-container {
    padding: 0 16px;
  }

  .form-card {
    padding: 16px;
  }

  .settings-container {
    grid-template-columns: 1fr;
    padding: 16px;
  }

  .form-section {
    gap: 24px;
  }
}

.custom-select {
  width: 100%;
}

/* 覆盖 Element UI 的默认样式 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-select__tags) {
  width: 100%;
  flex-wrap: wrap;
}

/* 确保下拉菜单也足够宽 */
:deep(.el-select-dropdown) {
  width: auto !important;
  min-width: 100% !important;
}

.ai-settings-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ai-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 8px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}
</style>